<template>
	<view class="u-form"><slot /></view>
</template>

<script>
	

export default {
	name: 'u-form',
	props: {
		
		model: {
			type: Object,
			default() {
				return {};
			}
		},
		
		
		
		
		
		
		
		
		
		errorType: {
			type: Array,
			default() {
				return ['message', 'toast']
			}
		},
		
		borderBottom: {
			type: Boolean,
			default: true
		},
		
		labelPosition: {
			type: String,
			default: 'left'
		},
		
		labelWidth: {
			type: [String, Number],
			default: 90
		},
		
		labelAlign: {
			type: String,
			default: 'left'
		},
		
		labelStyle: {
			type: Object,
			default() {
				return {}
			}
		},
	},
	provide() {
		return {
			uForm: this
		};
	},
	data() {
		return {
			rules: {}
		};
	},
	created() {
		
		
		this.fields = [];
	},
	methods: {
		setRules(rules) {
			this.rules = rules;
		},
		
		resetFields() {
			this.fields.map(field => {
				field.resetField();
			});
		},
		
		validate(callback) {
			return new Promise(resolve => {
				
				let valid = true; 
				let count = 0; 
				let errorArr = []; 
				this.fields.map(field => {
					
					field.validation('', error => {
						
						if (error) {
							valid = false;
							errorArr.push(error);
						}
						
						if (++count === this.fields.length) {
							resolve(valid); 
							
							if(this.errorType.indexOf('none') === -1 && this.errorType.indexOf('toast') >= 0 && errorArr.length) {
								this.$u.toast(errorArr[0]);
							}
							
							if (typeof callback == 'function') callback(valid);
						}
					});
				});
			});
		}
	}
};
</script>

<style scoped lang="scss">
@import "../../libs/css/style.components.scss";
</style>
